/*
 * @lc app=leetcode.cn id=636 lang=javascript
 *
 * [636] 函数的独占时间
 */

// @lc code=start
/**
 * @param {number} n
 * @param {string[]} logs
 * @return {number[]}
 */
var exclusiveTime = function (n, logs) {
  const result = new Array(n).fill(0);
  let preTimestamp = 0;
  const stack = [];

  for (let i = 0; i < logs.length; i++) {
    let [id, status, timestamp] = logs[i].split(':');
    id = Number(id);
    timestamp = Number(timestamp);

    // 给栈顶元素累加单位时间，注意判断是否是end状态
    if (stack.length) {
      let top = stack.length - 1;
      result[stack[top]] += timestamp - preTimestamp + (status === 'end' ? 1 : 0);
    }
    // 更新前一次的时间戳
    preTimestamp = timestamp + (status === 'end' ? 1 : 0);

    // 根据状态出入栈
    if (status === 'start') {
      stack.push(id);
    } else {
      stack.pop();
    }
  }

  return result;
};
// @lc code=end
